/**
 * @file optimizer.h
 * @brief IR优化器头文件
 * @author VimLVM Team
 * @date 2025
 */

#ifndef VIML_OPTIMIZER_H
#define VIML_OPTIMIZER_H

#include "common.h"
#include "instruction.h"
#include "value.h"
#include <memory>
#include <vector>
#include <unordered_map>

namespace viml {

// 前向声明
struct Function;
class VM;

/**
 * @brief 优化级别
 */
enum class OptimizationLevel {
    NONE,      // 无优化
    BASIC,     // 基础优化
    ADVANCED   // 高级优化
};

/**
 * @brief 优化统计信息
 */
struct OptimizationStats {
    size_t instructions_removed = 0;
    size_t instructions_replaced = 0;
    size_t constants_folded = 0;
    size_t dead_code_removed = 0;
    size_t common_subexpressions = 0;
    double optimization_time_ms = 0.0;
};

/**
 * @brief 内联缓存条目
 */
struct InlineCacheEntry {
    ValueType type;
    void* cached_value;
    uint64_t hit_count = 0;
    uint64_t miss_count = 0;
    
    double hit_rate() const {
        return hit_count + miss_count > 0 ? 
               static_cast<double>(hit_count) / (hit_count + miss_count) : 0.0;
    }
};

/**
 * @brief 内联缓存
 */
class InlineCache {
public:
    static constexpr size_t MAX_CACHE_SIZE = 8;
    
    InlineCache();  // 添加默认构造函数声明
    
    /**
     * @brief 获取缓存条目
     */
    InlineCacheEntry* get_entry(size_t index);
    
    /**
     * @brief 添加缓存条目
     */
    bool add_entry(const InlineCacheEntry& entry);
    
    /**
     * @brief 清除缓存
     */
    void clear();
    
    /**
     * @brief 获取统计信息
     */
    struct Stats {
        size_t total_lookups = 0;
        size_t cache_hits = 0;
        size_t cache_misses = 0;
        double hit_rate() const {
            return total_lookups > 0 ? static_cast<double>(cache_hits) / total_lookups : 0.0;
        }
    };
    
    Stats get_stats() const;

private:
    std::array<InlineCacheEntry, MAX_CACHE_SIZE> entries_;
    size_t size_ = 0;
    Stats stats_;
};

/**
 * @brief IR优化器
 */
class Optimizer {
public:
    Optimizer(OptimizationLevel level = OptimizationLevel::BASIC);
    
    /**
     * @brief 优化函数
     */
    std::shared_ptr<Function> optimize(const std::shared_ptr<Function>& function);
    
    /**
     * @brief 获取优化统计信息
     */
    const OptimizationStats& get_stats() const { return stats_; }
    
    /**
     * @brief 重置统计信息
     */
    void reset_stats();

private:
    OptimizationLevel level_;
    OptimizationStats stats_;
    
    // 优化pass
    void constant_folding(std::shared_ptr<Function>& function);
    void dead_code_elimination(std::shared_ptr<Function>& function);
    void common_subexpression_elimination(std::shared_ptr<Function>& function);
    void peephole_optimization(std::shared_ptr<Function>& function);
    void register_allocation(std::shared_ptr<Function>& function);
    
    // 辅助函数
    bool is_constant(const Value& value) const;
    bool is_pure_opcode(OpCode op) const;
    bool can_be_optimized(const Instruction& inst) const;
    
    // 内联缓存优化
    void inline_cache_optimization(std::shared_ptr<Function>& function);
};

/**
 * @brief 优化器工厂
 */
class OptimizerFactory {
public:
    static std::unique_ptr<Optimizer> create(OptimizationLevel level);
    static OptimizationLevel from_string(const std::string& level);
    static std::string to_string(OptimizationLevel level);
};

} // namespace viml

#endif // VIML_OPTIMIZER_H